package etcdgw

import (
	"context"
	"fronter/config"
	"os"
	"time"

	"github.com/coreos/etcd/clientv3"
	log "github.com/sirupsen/logrus"
)

var client *clientv3.Client

type KeyVal struct {
	Key string
	Val string
}

func init() {
	//配置文件读取etcd配置
	cfg := config.Get()
	etcdAddr := cfg.Etcd
	config := clientv3.Config{
		Endpoints:   etcdAddr,
		DialTimeout: 10 * time.Second,
	}
	var err error
	client, err = clientv3.New(config)
	if err != nil {
		log.Errorln("connect to etcd faile! please check! addr:", etcdAddr, " err:", err)
		os.Exit(-2)
	}
}

func SetKV(key string, val string) {
	kv := clientv3.NewKV(client)
	if _, err := kv.Put(context.TODO(), key, val); err != nil {
		log.Errorln("set kv failed! key:", key, " val:", val, " err:", err)
		return
	}
}
func GetKey(key string) *string {
	kv := clientv3.NewKV(client)
	getRes, err := kv.Get(context.TODO(), key)
	if err != nil {
		log.Errorln("get kv failed! key:", key, " err:", err)
		return nil
	}
	if getRes.Count == 0 {
		return nil
	}
	val := string(getRes.Kvs[0].Value)
	return &val
}

func GetKeys(key string) *[]KeyVal {
	kv := clientv3.NewKV(client)
	getRes, err := kv.Get(context.TODO(), key, clientv3.WithPrevKV())
	if err != nil {
		log.Errorln("get kv failed! key:", key, " err:", err)
		return nil
	}
	if getRes.Count == 0 {
		return nil
	}
	var kvs []KeyVal
	var i int64
	for i = 0; i < getRes.Count; i++ {
		kv := KeyVal{
			Key: string(getRes.Kvs[i].Key),
			Val: string(getRes.Kvs[i].Value),
		}
		kvs = append(kvs, kv)
	}
	return &kvs
}

func watchImpl(key string, cb func(*clientv3.Event)) {
	rch := client.Watch(context.Background(), key)
	for wresp := range rch {
		for _, ev := range wresp.Events {
			cb(ev)
		}
	}
}

func Watch(key string, cb func(*clientv3.Event)) {
	go watchImpl(key, cb)
}
